package com.ougy.reshop.test.network;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class BaseHttpUtil {

	public static String sendGet(String url, Map<String, String> paramsPair) {
		String result = null;
		BufferedReader in = null;
		try {
			StringBuffer sb = new StringBuffer(url);
			if (paramsPair != null && paramsPair.size() > 0) {
				sb.append("?");
				for (String key : paramsPair.keySet()) {
					if (sb.length() != (url.length() + 1)) {
						sb.append("&");
					}
					sb.append(key).append("=").append(paramsPair.get(key));
				}
			}
			URLConnection conn = new URL(sb.toString()).openConnection();
			conn.connect();
			Map<String, List<String>> map = conn.getHeaderFields();
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += "/n" + line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static void downloadFile(String urlPath, String filePath) {
		OutputStream os = null;
		InputStream is = null;
		try {
			URL url = new URL(urlPath);
			File outFile = new File(filePath);
			os = new FileOutputStream(outFile);
			is = url.openStream();
			byte[] buff = new byte[1024];
			while (true) {
				int readed = is.read(buff);
				if (readed == -1) {
					break;
				}
				byte[] temp = new byte[readed];
				System.arraycopy(buff, 0, temp, 0, readed);
				os.write(temp);
			}
		} catch (Exception e) {
			System.out.println("发送downloadFile出现异常！" + e);
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}


}
